package cn.itcast.demo.pojo;

import lombok.Data;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
@Data
public class DelayTask implements Delayed {

    /**
     * 结束时间
     */
    private long endTime;

    private Object data;

    public DelayTask(long delayTime, Object data) {
        this.endTime = System.currentTimeMillis() + delayTime;
        this.data = data;
    }

    /**
     * 返回的是剩余有效期
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(endTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    /**
     * 比较两个任务的剩余有效期
     */
    @Override
    public int compareTo(Delayed o) {
        long r = this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
        return  r > 0 ? 1 : (r == 0 ? 0 : -1);
    }
}
